package com.atguigu.servicevod.controller;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.commonutils.Result;
import com.atguigu.servicebase.handler.CustomException;
import com.atguigu.servicevod.constant.ConstantPropertiesUtil;
import com.atguigu.servicevod.service.VideoService;
import com.atguigu.servicevod.util.InitVideoClientUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
@RestController
@RequestMapping("/eduvod/vod/")
@Api(value="阿里云视频点播微服务")
@CrossOrigin //跨域
public class uploadController {

  	@Resource
	private VideoService videoService;

	@PostMapping("/upload")
	public Result uploadVideo(
			@ApiParam(name = "file", value = "文件", required = true)
			@RequestParam("file") MultipartFile file) throws Exception {

		String videoId = videoService.uploadVideo(file);
		return Result.ok().message("视频上传成功").data("videoId", videoId);
	}


	@DeleteMapping("/removeVideo/{videoId}")
	public Result removeVideo(@ApiParam(name = "videoId", value = "云端视频id", required = true)
						 @PathVariable String videoId){

		videoService.removeVideo(videoId);
		return Result.ok().message("视频删除成功");
	}


	/**
	 * 前端根据视频的id获取视频的播放凭证
	 * @param AuthId
	 * @return
	 */

	@GetMapping("/getPlayAuth/{AuthId}")
	public Result getPlayAuth(@PathVariable String AuthId){
		GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
		GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();

		try {
			//根据视频的id获取凭证
			//初始化客户端、请求对象和相应对象
			DefaultAcsClient client = InitVideoClientUtil.initVodClient(
					ConstantPropertiesUtil.ACCESS_KEY_ID,
					ConstantPropertiesUtil.ACCESS_KEY_SECRET);

			//设置请求参数
			request.setVideoId(AuthId);
			//获取请求响应
			response = client.getAcsResponse(request);
		} catch (ClientException e) {
			throw new CustomException(20001,"获取视频凭证失败");
		}
		String playAuth = response.getPlayAuth();
		return Result.ok().data("playAuth",playAuth);

	}


}
